package com.linkage.usercenter.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.linkage.common.base.LocationVo;
import com.linkage.common.constant.CommonSysConstant;
import com.linkage.common.exception.ServiceException;
import com.linkage.common.util.RedisUtils;
import com.linkage.usercenter.config.constant.PhoneThirdSysConstant;
import com.linkage.usercenter.dao.*;
import com.linkage.usercenter.feign.HomeManageFeign;
import com.linkage.usercenter.feign.PhoneManageFeign;
import com.linkage.usercenter.pojo.entity.*;
import com.linkage.usercenter.pojo.vo.*;
import com.linkage.usercenter.service.IManageService;
import com.linkage.usercenter.utils.TableCommonDataUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service
public class ManageOperationServiceImpl implements IManageService {

    private static final Logger logger = LoggerFactory.getLogger(ManageOperationServiceImpl.class);

    @Autowired
    private CoreUserMapper userDao;

    @Autowired
    private CorePersonInfoMapper personDao;

    @Autowired
    private UserSubInfoMapper userSubInfoDao;


    @Autowired
    private CoreDptInfoMapper dptInfoDao;

    @Autowired
    private CoreRoleMapper roleDao;

    @Autowired
    private CoreOperateMapper operatorDao;

    @Autowired
    private CoreMiddleUserRoleMapper middleUserRoleDao;

    @Autowired
    private CoreMiddleOperateRoleMapper middleOperateRoleDao;

    @Autowired
    private DptSubInfoMapper dptSubInfoDao;

    @Resource
    private RedisUtils redisUtils;

    @Autowired
    private PhoneManageFeign phoneManageFeign;

    @Value("${customer.third-platform-config.third-phone-appkey}")
    private String  appkey;


    // //根据机构查询部门信息   (  1保安 2警察 6  9 所有)
    @Override
    public List<DptInfoLevelVO> getDptList(String orgCode) {
        List<DptInfoLevelVO> resultList = new ArrayList<DptInfoLevelVO>();
        String realOrgCode = "";
        switch (orgCode) {
            case "1":
                realOrgCode = CommonSysConstant.ORG_CODE_TYPE_5 ;
                break;
            case "2":
                realOrgCode = CommonSysConstant.ORG_CODE_POLICE ;
                break;
            case "6":
                realOrgCode = CommonSysConstant.ORG_CODE_TYPE_6 ;
                break;
            case "9":
                realOrgCode = CommonSysConstant.ORG_CODE_ALL ;
                break;
            default:
                realOrgCode = "" ;
                break;
        }
        if(StrUtil.isBlank(realOrgCode)){
            throw new ValidateException("无相应类型的机构信息！");
        }

        List<CoreDptInfo> dptlist = null;
        if( CommonSysConstant.ORG_CODE_ALL.equals(realOrgCode) ){
            dptlist = dptInfoDao.queryAllRecordByLevel();
        }else{
            dptlist = dptInfoDao.queryByOrgCodeAndLevel(realOrgCode);
        }
        if( dptlist == null || dptlist.isEmpty()){
            return resultList;
        }
        for (CoreDptInfo coreDptInfo : dptlist) {
            DptInfoLevelVO dptInfoLevelVO = this.covertDOToVO(coreDptInfo);
            resultList.add(dptInfoLevelVO);
            if(CommonSysConstant.ORG_CODE_TYPE_5.equals(dptInfoLevelVO.getOrgCode())){
                //企业特殊处理
                this.getSubDptComList(dptInfoLevelVO);

            }else{
                this.getSubDptList(dptInfoLevelVO);
            }
        }
        return resultList;
    }

    private DptInfoLevelVO covertDOToVO(CoreDptInfo coreDptInfo) {
        if(coreDptInfo == null ){
            return null;
        }
        DptInfoLevelVO dptInfoLevelVO = new DptInfoLevelVO();
        dptInfoLevelVO.setDptCode(coreDptInfo.getDptCode());
        dptInfoLevelVO.setDptName(coreDptInfo.getDptName());
        dptInfoLevelVO.setDptParentCode(coreDptInfo.getDptParentCode());
        dptInfoLevelVO.setDptLevel(coreDptInfo.getDptLevel());
        dptInfoLevelVO.setDptDesc(coreDptInfo.getDptDesc());
        dptInfoLevelVO.setOrgCode(coreDptInfo.getDptOrgCode());
        String dptUserkeyToken = "TOKEN:"+coreDptInfo.getDptCode().trim()+":"+CommonSysConstant.PERSON_GLY12_FLAG+":*";
        dptInfoLevelVO.setLineFlag(redisUtils.keysAndExsit(dptUserkeyToken) ? "1":"0");
        return dptInfoLevelVO;
    }

    //树形添加子机构
    private void getSubDptList(DptInfoLevelVO dptInfoLevelVO) {
        if(dptInfoLevelVO == null){
            return;
        }
        String dptCode = dptInfoLevelVO.getDptCode();
        List<CoreDptInfo>  dptDOList = dptInfoDao.queryByParentCode(dptCode);
        if(dptDOList == null || dptDOList.isEmpty()){
            return;
        }
        List<DptInfoLevelVO> voList = new ArrayList<DptInfoLevelVO>();
        for (CoreDptInfo dptDO : dptDOList) {
            DptInfoLevelVO vo = this.covertDOToVO(dptDO);
            voList.add(vo);
            this.getSubDptList(vo);
        }
        dptInfoLevelVO.setSubDptList(voList);

    }


    //树形添加子机构
    private void getSubDptCodeList(String dptCode, List<String> allDptCodeList) {
        if(StrUtil.isBlank(dptCode)){
            return;
        }
        allDptCodeList.add(dptCode);
        List<String>  dptCodeList = dptInfoDao.queryCodeByParentCode(dptCode);
        if(dptCodeList == null || dptCodeList.isEmpty()){
            return;
        }
        for (String subDptCode : dptCodeList) {
            this.getSubDptCodeList(subDptCode, allDptCodeList);
        }
    }

    //添加子机构
    private void addSubDptInfo(List<CoreDptInfo> dptlist, CoreDptInfo coreDptInfo) {
        if(coreDptInfo == null){
            return;
        }
        List<CoreDptInfo> subDptList = dptInfoDao.querySubRecordByDptCode(coreDptInfo.getDptCode());
        if(!subDptList.isEmpty()){
            for (CoreDptInfo dptInfo : subDptList) {
                dptlist.add(dptInfo);
                this.addSubDptInfo(dptlist, dptInfo);
            }
        }

    }


    //根据部门代码查询部门所有人员信息
    @Override
    public List<UserMgInfoVO> getDptUserInfo(String dptCode) {
        List<UserMgInfoVO> resultList = new ArrayList<UserMgInfoVO>();
        List<CorePersonInfo> userDOList = personDao.getRecordByDptCode(dptCode,null);
        if(userDOList == null || userDOList.isEmpty()){
            return resultList;
        }
        for (CorePersonInfo personInfoDO : userDOList) {
            if(CommonSysConstant.PERSON_CLASS_THREE.equals(personInfoDO.getPersonClass() )
                    || CommonSysConstant.PERSON_CLASS_FOUR.equals(personInfoDO.getPersonClass())
                    || CommonSysConstant.PERSON_CLASS_NINE.equals(personInfoDO.getPersonClass())
                    || CommonSysConstant.PERSON_CLASS_FIVE.equals(personInfoDO.getPersonClass())){
                continue;
            }
            CoreUser userDO = userDao.getRecordByPersonCode(personInfoDO.getPersonCode());
            if(userDO == null){
                logger.error("查询用户信息失败！PersonCode:"+personInfoDO.getPersonCode());
                continue;
            }
            String userCode = userDO.getUserCode();
            UserSubInfo userSubInfoDO = userSubInfoDao.selectByPrimaryKey(userCode);
            List<CoreRole> roleList = roleDao.queryRoleInfosByUserCode(userCode);
            UserMgInfoVO vo = this.genUserMgInfoVO(personInfoDO, userDO, userSubInfoDO,  roleList);
            resultList.add(vo);
        }
        return resultList;
    }


    //根据手机号 身份证 或用户编码查询人员信息
    @Override
    public UserMgInfoVO getUserMgInfoVO(String param) {
        CoreUser userDO = null;
        //用户编码
        List<CoreUser> userDOList = userDao.getAllRecordByUserCode(param);
        if(userDOList== null || userDOList.isEmpty() || userDOList.size()>1){
            logger.error("查询用户信息失败！userCode:"+param);
            throw new ServiceException(1,"查询用户信息失败！userCode:"+param);
        }
        userDO = userDOList.get(0);
        if(userDO == null){
            logger.error("查询用户信息失败！param:"+param);
        }
        CorePersonInfo personInfoDO = personDao.getRecordByPersonCode(userDO.getUserPersonCode());
        if(personInfoDO == null){
            logger.error("查询用户详细信息失败！param:"+param);
        }
        String userCode = userDO.getUserCode();
        UserSubInfo userSubInfoDO = userSubInfoDao.selectByPrimaryKey(userCode);
        List<CoreRole> roleList = roleDao.queryRoleInfosByUserCode(userCode);
        UserMgInfoVO vo = this.genUserMgInfoVO(personInfoDO, userDO, userSubInfoDO,  roleList);
        return vo;
    }

    //根据手机号 身份证 或用户编码 用户姓名查询人员信息
    @Override
    public List<UserMgInfoVO> getUserMgInfoVOList(String param, CoreUser userInfoToken) {
        List<UserMgInfoVO> list = new ArrayList<UserMgInfoVO>();
        CorePersonInfo personInfo = personDao.getRecordByPersonCode(userInfoToken.getUserPersonCode());
        boolean cjFlag = false;
        if(personInfo != null
                && CommonSysConstant.PERSON_CLASS_THREE.equals(personInfo.getPersonClass())){
            //超级管理员
            cjFlag = true;
        }
        List<String> allDptCodeList = new ArrayList<String>();
        if(!cjFlag){
            String dptCode = dptInfoDao.getDptCodeByUserCode(userInfoToken.getUserCode());
            if(StrUtil.isBlank(dptCode)){
                logger.error("查询机构代码为空!");
                return list;
            }
            CoreDptInfo dptInfoDO = dptInfoDao.queryByDptCode(dptCode).isEmpty()
                    ?  null :  dptInfoDao.queryByDptCode(dptCode).get(0);
            if(ObjectUtil.isNull(dptInfoDO) ){
                logger.error("查询机构信息为空!");
                return list;
            }
            allDptCodeList.add(dptCode);
            //添加子机构代码
            this.getSubDptDOCodeList(allDptCodeList, dptInfoDO);
        }

        List<CoreUser> userDOList = new ArrayList<CoreUser>();
        if (Validator.isMobile(param)) {
            //手机号
            CoreUser userDO = userDao.getRecordByMobile(param);
            userDOList.add(userDO);
        } else if (IdcardUtil.isValidCard(param)) {
            //身份证号码
            CoreUser userDO = userDao.getRecordByCardNo(param);
            userDOList.add(userDO);
        } else {
            //用户编码 或姓名
//            userDOList = userDao.getAllRecordByUserCode(param);
            userDOList = userDao.getAllRecordByUserCodeAndName(param);
            if (userDOList == null || userDOList.isEmpty() || userDOList.size() > 1) {
                logger.error("查询用户信息失败！userCode:" + param);
            }
        }
        if(userDOList==null || userDOList.isEmpty()){
            return list;
        }
        for (CoreUser coreUser : userDOList) {
            if (coreUser == null) {
                continue;
            }
            CorePersonInfo personInfoDO = personDao.getRecordByPersonCode(coreUser.getUserPersonCode());
            if (personInfoDO == null) {
                logger.error("查询用户详细信息失败！userCode:" + coreUser.getUserCode());
                continue;
            }
            if(!cjFlag){
                if(!allDptCodeList.contains(personInfoDO.getPersonOrgCode())){
                    logger.info("该用户不属于其下属机构人员：{}", personInfoDO.getPersonRealName());
                    continue;
                }
            }
            String userCode = coreUser.getUserCode();
            UserSubInfo userSubInfoDO = userSubInfoDao.selectByPrimaryKey(userCode);
//            List<CoreRole> roleList = roleDao.queryRoleInfosByUserCode(userCode);
            UserMgInfoVO vo = this.genUserMgInfoVO(personInfoDO, coreUser, userSubInfoDO, null);
            list.add(vo);
        }
        //处理人员位置和在线状态
        this.dealUserLineAncLocation(list);
        return list;
    }

    //根据手机号 或 用户姓名查询待审核保安人员信息
    @Override
    public List<UserMgInfoVO> getAuditEmpList(String param,  CoreUser userInfoToken, String checkFlag, String personClass) {
        List<UserMgInfoVO> list = new ArrayList<UserMgInfoVO>();
        CorePersonInfo personInfo = personDao.getRecordByPersonCode(userInfoToken.getUserPersonCode());
        String userPhoneFlag = personInfo.getPersonPhoneFlag();
        boolean cjFlag = false;
        if(personInfo != null
                && (CommonSysConstant.PERSON_CLASS_THREE.equals(personInfo.getPersonClass())
                || CommonSysConstant.PERSON_CLASS_NINE.equals(personInfo.getPersonClass()))
        ){
            //超级管理员或运营商
            cjFlag = true;
        }
        List<String> allDptCodeList = new ArrayList<String>();
        if(!cjFlag){
            String dptCode = dptInfoDao.getDptCodeByUserCode(userInfoToken.getUserCode());
            if(StrUtil.isBlank(dptCode)){
                logger.error("查询机构代码为空!");
                return list;
            }
            CoreDptInfo dptInfoDO = dptInfoDao.queryByDptCode(dptCode).isEmpty()
                    ?  null :  dptInfoDao.queryByDptCode(dptCode).get(0);
            if(ObjectUtil.isNull(dptInfoDO) ){
                logger.error("查询机构信息为空!");
                return list;
            }
            allDptCodeList.add(dptCode);
            //添加子机构代码
            this.getSubDptDOCodeList(allDptCodeList, dptInfoDO);
        }

        List<CoreUser> userDOList = new ArrayList<CoreUser>();
        if(StrUtil.isNotBlank(param)){
            if (Validator.isMobile(param)) {
                //手机号
                CoreUser userDO = userDao.selectByUserCode(param);
                userDOList.add(userDO);
            }else {
                // 姓名
                userDOList = userDao.getAllRecordByUserName(param);
                if (userDOList == null || userDOList.isEmpty() || userDOList.size() > 1) {
                    logger.error("查询用户信息失败！userCode:" + param);
                }
            }
        }else{
            //所有符合审核的人员信息
            userDOList = userDao.getAllRecordForAudit(personClass);
        }

        if(CollUtil.isEmpty(userDOList) ){
            return list;
        }
        for (CoreUser coreUser : userDOList) {
            if (coreUser == null) {
                continue;
            }
            CorePersonInfo personInfoDO = personDao.getRecordByPersonCode(coreUser.getUserPersonCode());
            if(null == personInfoDO){
                continue;
            }
            if (!personClass.equals(personInfoDO.getPersonClass()) ) {
                logger.error("查询用户详细信息，不符合条件！personClass:" + personClass);
                continue;
            }
            if(!cjFlag){
                if(!allDptCodeList.contains(personInfoDO.getPersonOrgCode())){
                    logger.info("该用户不属于其下属机构人员：{}", personInfoDO.getPersonRealName());
                    continue;
                }
            }
            //0：正常-审核通过；1：离职-审核拒绝,2：初始化
            if(StrUtil.isNotBlank(checkFlag)){
                if(!checkFlag.equals(personInfoDO.getPersonJobFlag())){
                    logger.info("该用户审核状态不匹配：{}", personInfoDO.getPersonRealName());
                    continue;
                }
            }
            //运营商审核对应得运营商手机号保安人员
            if(CommonSysConstant.PERSON_CLASS_NINE.equals(personInfo.getPersonClass())
                    && CommonSysConstant.PERSON_CLASS_ONE.equals(personInfoDO.getPersonClass())
                    && StrUtil.isNotBlank(userPhoneFlag) ){
                if(!userPhoneFlag.equals(personInfoDO.getPersonPhoneFlag())){
                    logger.info("该用户不属于对应运营商人员：{}", personInfoDO.getPersonRealName());
                    continue;
                }
            }
            String userCode = coreUser.getUserCode();
            UserSubInfo userSubInfoDO = userSubInfoDao.selectByPrimaryKey(userCode);
//            List<CoreRole> roleList = roleDao.queryRoleInfosByUserCode(userCode);
            UserMgInfoVO vo = this.genUserMgInfoVO(personInfoDO, coreUser, userSubInfoDO, null);
            list.add(vo);
        }
//        //处理人员位置和在线状态
//        this.dealUserLineAncLocation(list);
        return list;
    }

    //根据机构代码查部门信息
    @Override
    public List<DptInfoVO> getDptInfos(String orgCode) {
        List<DptInfoVO> list = CollUtil.newArrayList();
        List<CoreDptInfo> dptDOList = null;
        if(StrUtil.isNotBlank(orgCode)){
            dptDOList = dptInfoDao.queryByOrgCode(orgCode);
        }else {
            dptDOList = dptInfoDao.queryAllRecord();
        }
        if(CollUtil.isNotEmpty(dptDOList)){
            dptDOList.stream().forEach( x -> {
                DptInfoVO vo = new DptInfoVO();
                list.add(vo);
                vo.setDptCode(x.getDptCode());
                vo.setDptName(x.getDptName());
                vo.setDptLevel(x.getDptLevel());
                vo.setDptParentCode(x.getDptParentCode());
                vo.setDptDesc(x.getDptDesc());
            });
        }
        return list;
    }

    /**
     * 手机号运营商查询
     * @param phoneList
     */
    @Override
    public void mobileTransfer(List<String> phoneList) {
        long bgTime = System.currentTimeMillis();
        if(CollUtil.isEmpty(phoneList)){
            return;
        }
        phoneList.stream().forEach( userMobile -> {
            if(Validator.isMobile(userMobile)){
                try {
                    logger.info("调用手机号运营商查询接口开始！ 入参：" + JSON.toJSONString(userMobile));
                    String backString = phoneManageFeign.mobileTransfer(userMobile, appkey);
                    logger.info("调用手机号运营商查询接口结束！ 耗时： {} ms",(System.currentTimeMillis()-bgTime)+"" );
                    this.updatePhoneFlagByMobile(userMobile, backString);
                }catch (Exception e){
                    logger.error("手机号运营商更新失败！手机号：" + userMobile,e);
                }

            }
        });
    }

    /**
     * 更新手机运营商
     * @param mobiles
     */
    @Override
    public void updatePhoneFlag(String mobiles) {
        if(StrUtil.isBlank(mobiles)){
            //更新全部保安的手机运营商
            List<String> mobileList = personDao.getMobilesByPhoneFlag();
            this.mobileTransfer(mobileList);
            return;
        }
        String splitFlag = ",";
        if(mobiles.contains(splitFlag)){
            String[] mobileArray = mobiles.split(splitFlag);
            this.mobileTransfer(Arrays.asList(mobileArray));
        }else if(Validator.isMobile(mobiles)){
            this.mobileTransfer(Arrays.asList(mobiles));
        }
    }

    private void updatePhoneFlagByMobile(String mobile, String backString){
        if(StrUtil.hasBlank(mobile, backString)){
            logger.info("手机号运营商查询接口返回报文为空！手机号：{}", mobile);
            return;
        }
        logger.info("调用手机号运营商查询结果:{}", backString);
        JSONObject backObj = JSON.parseObject(backString);
        if(ObjectUtil.isNull(backObj)){
            logger.info("手机号运营商查询接口返回报文无法解析！返回报文内容：{}", backString);
            return;
        }
        if(!StrUtil.equals(PhoneThirdSysConstant.CODE_FLAG, backObj.getString(PhoneThirdSysConstant.CODE_CODE))){
            logger.info("手机号运营商查询接口调用异常！错误信息：{} ", backObj.getString(PhoneThirdSysConstant.CODE_MSG));
            return;
        }
        logger.info("手机号运营商查询接口调用成功！");
        JSONObject resultObj = backObj.getJSONObject(PhoneThirdSysConstant.CODE_RESULT);
        if(ObjectUtil.isNull(resultObj)){
            logger.info("手机号运营商查询结果为空！返回报文内容：{}", backObj.toJSONString());
            return;
        }
        if(!StrUtil.equals(PhoneThirdSysConstant.SUB_CODE_FLAG, resultObj.getString(PhoneThirdSysConstant.CODE_CODE))){
            logger.info("手机号运营商查询结果异常！错误信息：{} ", resultObj.getString(PhoneThirdSysConstant.CODE_MSG));
            return;
        }

        JSONObject dataObj = resultObj.getJSONObject(PhoneThirdSysConstant.CODE_DATA);
        if(ObjectUtil.isNull(dataObj)){
            logger.info("手机号信息为空！返回报文内容：{}", resultObj.toJSONString());
            return;
        }
        logger.info("手机号运营商查询结果成功！");
        // 电话归属运营商（1 移动 ，2 联通 ， 3 电信 9 未知）
        String phoneFlag = "9";
        String phoneYYSFlag = dataObj.getString(PhoneThirdSysConstant.CODE_NEWISPTYPE);
        if(PhoneThirdSysConstant.LIANT_FLAG.equals(phoneYYSFlag)){
            phoneFlag = "2";
        }else if(PhoneThirdSysConstant.DIANX_FLAG.equals(phoneYYSFlag)){
            phoneFlag = "3";
        }else if(PhoneThirdSysConstant.YID_FLAG.equals(phoneYYSFlag)){
            phoneFlag = "1";
        }
        personDao.updatePersonPhoneFlag(mobile, phoneFlag);
        logger.info("手机号运营商更新成功！手机号：{}; 运营商：{}; phoneFlag：{}", mobile, phoneYYSFlag, phoneFlag);
    }

    //查询所属子机构代码
    private void getSubDptDOCodeList(List<String> allDptCodeList, CoreDptInfo dptInfoDO) {
        if(CommonSysConstant.ORG_CODE_TYPE_5.equals(dptInfoDO.getDptOrgCode())){
            //企业特殊处理
            this.getSubDptComCodeList(dptInfoDO.getDptCode(), allDptCodeList);

        }else{
            this.getSubDptCodeList(dptInfoDO.getDptCode(), allDptCodeList);
        }
    }

    @Override
    public UserMgInfoVO getSuperiorManager(String userCode) {
        CorePersonInfo personInfo = personDao.getRecordByUserCode(userCode);
        if(ObjectUtil.isNull(personInfo)){
            logger.error("查询所属部门为空");
            return null;
        }
        String deptCode = null;
        //如果当前用户为管理员，则查询上级部门管理员
        if("4,5".contains(personInfo.getPersonClass())){
            CoreDptInfo dept = dptInfoDao.queryParentDptByUserCode(userCode);
            if(StrUtil.isEmpty(dept.getDptParentCode())){
                deptCode = dept.getDptCode();
            }else{
                deptCode = dept.getDptParentCode();
            }
        }else{
            deptCode = personInfo.getPersonOrgCode();
        }
        //根据personinfo表查询personclass区分角色
        List<CoreUser> userList = userDao.queryUserByDptWithPersonClass(deptCode,"4");
        CoreUser user = null;
        if(ObjectUtil.isNotEmpty(userList)){
            user = userList.get(0);
        }else{
            throw new ServiceException(500,"未找到对应的一级管理员");
        }
        return UserMgInfoVO.builder().personOrgCode(deptCode)
                .userCode(user.getUserCode()).userMobile(user.getUserMobile()).build();
    }

    @Override
    public List<CodeOperateVO> queryAllOperatorInfos(String param, CoreUser userInfoToken) {
        CorePersonInfo personInfo = personDao.getRecordByPersonCode(userInfoToken.getUserPersonCode());
        if(personInfo == null){
            throw new ValidateException("查询登录用户人员信息失败！");
        }
        if(StrUtil.isBlank(param)){
            //默认验收数据
            param = "6";
        }
        if(CommonSysConstant.PERSON_CLASS_FIVE.equals(personInfo.getPersonClass())){
            throw new ValidateException("二级管理员无此权限！");
        }
        List<CodeOperateVO>  resultList = new ArrayList<CodeOperateVO>();
        List<CoreOperate>  doList  = operatorDao.queryRecordsByStatus(param);
        if(CommonSysConstant.PERSON_CLASS_FOUR.equals(personInfo.getPersonClass())){
            List<CoreRole>  roleDOList = roleDao.queryRoleInfosByUserCode(userInfoToken.getUserCode());
            if(!CollUtil.isEmpty(roleDOList)){
                doList.clear();
                roleDOList.forEach(x ->{
                    List<CoreOperate>  operateDOList = operatorDao.queryRecorRoleCode(x.getRoleCode());
                    doList.addAll(operateDOList);
                });
            }
        }
        if(doList != null && doList.size() > 0 ){
            doList.forEach(x->{
                if(CommonSysConstant.PERSON_CLASS_THREE.equals(personInfo.getPersonClass())){
                    logger.info("超级管理员查询权限特殊处理");
                    //OPR-9009	运营商
                    CodeOperateVO vo = new CodeOperateVO();
                    vo.setOperateCode(x.getOperateCode());
                    vo.setOperateName(x.getOperateName());
                    resultList.add(vo);
                }else{
                    if(!CommonSysConstant.OPR_CODE_YYS.equals(x.getOperateCode())){
                        CodeOperateVO vo = new CodeOperateVO();
                        vo.setOperateCode(x.getOperateCode());
                        vo.setOperateName(x.getOperateName());
                        resultList.add(vo);
                    }
                }
            });
        }

        return resultList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setOperatorGrop(MgRoleQUERY requestInfo, CoreUser user) {
        if(requestInfo==null  || requestInfo.getOperCodeList() == null || requestInfo.getOperCodeList().isEmpty()){
            throw new ValidateException("权限分组信息入参不完整，请检查！");
        }
        if(CommonSysConstant.CODE_ZERO.equals(requestInfo.getAddFlag())){
            //修改
            String roleCode = requestInfo.getRoleCode();
            if(StrUtil.isBlank(roleCode)){
                throw new ValidateException("修改权限分组信息，权限分组编码不能为空！");
            }
            CoreRole coreRoleDO = roleDao.getByRoleCode(roleCode);
            if(coreRoleDO == null){
                throw new ValidateException("该权限分组信息不存在，请检查！");
            }
            if(!StrUtil.equals(coreRoleDO.getCreateCode(), user.getUserCode())){
                throw new ValidateException("该权限分组信息不属于自身，无权操作！");
            }

            String roleName = requestInfo.getRoleName();
            if(StrUtil.isNotBlank(roleName)
                    && !StrUtil.equals(coreRoleDO.getRoleName(), roleName)){
                coreRoleDO.setRoleName(roleName);
            }
            middleOperateRoleDao.deleteByRoleCode(roleCode);
            for (String operCode : requestInfo.getOperCodeList()) {
                CoreMiddleOperateRole midOreRoleInfo = new CoreMiddleOperateRole();
                midOreRoleInfo.setMiddleOperateCode(operCode);
                midOreRoleInfo.setMiddleRoleCode(requestInfo.getRoleCode());
                TableCommonDataUtil.dealCrtUpdTableField(user.getUserCode(), midOreRoleInfo);
                middleOperateRoleDao.insert(midOreRoleInfo);
            }
            TableCommonDataUtil.dealCrtUpdTableField(user.getUserCode(), coreRoleDO);
            roleDao.updateByPrimaryKey(coreRoleDO);
        }else{
            if(StrUtil.isBlank(requestInfo.getRoleName())){
                throw new ValidateException("新增权限分组信息，权限分组名称不能为空！");
            }
            CoreRole coreRoleDO = new CoreRole();
            coreRoleDO.setRoleCode(IdUtil.simpleUUID());
            coreRoleDO.setRoleName(requestInfo.getRoleName());
            coreRoleDO.setRoleStatus(CommonSysConstant.CODE_ONE);
            for (String operCode : requestInfo.getOperCodeList()) {
                CoreMiddleOperateRole midOreRoleInfo = new CoreMiddleOperateRole();
                midOreRoleInfo.setMiddleOperateCode(operCode);
                midOreRoleInfo.setMiddleRoleCode(coreRoleDO.getRoleCode());
                TableCommonDataUtil.dealCrtUpdTableField(user.getUserCode(), midOreRoleInfo);
                middleOperateRoleDao.insert(midOreRoleInfo);
            }
            TableCommonDataUtil.dealCrtUpdTableField(user.getUserCode(), coreRoleDO);
            roleDao.insert(coreRoleDO);
        }
    }

    @Override
    public List<MgRoleVO> queryOwerOperatorGrop(CoreUser userInfoToken) {
        List<MgRoleVO>  resultList = new ArrayList<MgRoleVO>();
        List<CoreRole> doList = roleDao.queryRecordsByOwer(userInfoToken.getUserCode());
        if(doList != null && doList.size() > 0 ){
            for (CoreRole x : doList) {
                MgRoleVO vo = new MgRoleVO();
                vo.setRoleCode(x.getRoleCode());
                vo.setRoleName(x.getRoleName());
                resultList.add(vo);
            }
        }
        return resultList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delUserByUsercode(String param, CoreUser userInfoToken) {
        List<CoreUser> userList = userDao.getAllRecordByUserCode(param);
        if(checkListEmpty(userList)){
            throw new ValidateException("未查询到该用户信息！ userCode："+param);
        }
        if(userList.size() > 1 ){
            throw new ValidateException("用户信息异常，查询到多条记录！ userCode："+param);
        }
        CoreUser userDO = userList.get(0);
        CorePersonInfo personInfoDO = personDao.getRecordByPersonCode(userDO.getUserPersonCode());
        personInfoDO.setPersonOrgCode(CommonSysConstant.UNKNOW_DPT_CODE);
        personInfoDO.setPersonOrgName(CommonSysConstant.UNKNOW_DPT_NAME);
        userDO.setUserDelFlag(CommonSysConstant.CODE_ONE);
        personInfoDO.setPersonDelFlag(CommonSysConstant.CODE_ONE);
        userDO.setUserStatus(CommonSysConstant.CODE_ZERO);
        personInfoDO.setPersonStatus(CommonSysConstant.CODE_ZERO);
        TableCommonDataUtil.dealCrtUpdTableField(userInfoToken.getUserCode(), userDO, personInfoDO);
        userDao.updateByPrimaryKey(userDO);
        personDao.updateByPrimaryKey(personInfoDO);

    }

    @Override
    public List<UserMgInfoVO> getOwerUserInfo(String userType, CoreUser userInfoToken) {
        CorePersonInfo personInfo = personDao.getRecordByPersonCode(userInfoToken.getUserPersonCode());
        List<UserMgInfoVO> resultList = new ArrayList<UserMgInfoVO>();
        List<CorePersonInfo> userDOList = personDao.getRecordByCrtCode(userInfoToken.getUserCode());
        if(this.checkListEmpty(userDOList)){
            return resultList;
        }
        for (CorePersonInfo personInfoDO : userDOList) {
            if(personInfo != null && CommonSysConstant.PERSON_CLASS_THREE.equals(personInfo.getPersonClass())){
                if(!CommonSysConstant.PERSON_CLASS_FIVE.equals(personInfoDO.getPersonClass()) || !CommonSysConstant.PERSON_CLASS_NINE.equals(personInfoDO.getPersonClass())){
                    continue;
                }
            }else{
                if(!CommonSysConstant.PERSON_CLASS_FIVE.equals(personInfoDO.getPersonClass())){
                    continue;
                }
            }
            CoreUser userDO = userDao.getRecordByPersonCode(personInfoDO.getPersonCode());
            if(userDO == null){
                logger.error("查询用户信息失败！PersonCode:"+personInfoDO.getPersonCode());
                continue;
            }
            String userCode = userDO.getUserCode();
            UserSubInfo userSubInfoDO = userSubInfoDao.selectByPrimaryKey(userCode);
            List<CoreRole> roleList = roleDao.queryRoleInfosByUserCode(userCode);
            UserMgInfoVO vo = this.genUserMgInfoVO(personInfoDO, userDO, userSubInfoDO,  roleList);
            resultList.add(vo);
        }
        return resultList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delUserOprInfo(UserMgDeleteQUERY requestInfo, CoreUser userInfoToken) {
        if(StrUtil.isBlank(requestInfo.getUserCode()) ){
            throw new ValidateException("参数不完整！ userCode不能为空。");
        }
        String userCode = requestInfo.getUserCode();
        List<CoreUser> userList = userDao.getAllRecordByUserCode(userCode);
        if(checkListEmpty(userList)){
            throw new ValidateException("未查询到该用户信息！ userCode："+userCode);
        }
        if(userList.size() > 1 ){
            throw new ValidateException("用户信息异常，查询到多条记录！ userCode："+userCode);
        }
        CoreUser deleteUser = userList.get(0);
        userDao.deleteByPrimaryKey(deleteUser.getId());
        personDao.deleteByPersonCode(deleteUser.getUserPersonCode());
        userSubInfoDao.deleteByPrimaryKey(userCode);
        middleUserRoleDao.deleteByUserCode(userCode);
    }

    @Override
    public List<DptInfoLevelVO> getOwerDptList(String paramVar, CoreUser userInfoToken) {
        List<DptInfoLevelVO> resultList = new ArrayList<DptInfoLevelVO>();
        CorePersonInfo personInfoDO = personDao.getRecordByPersonCode(userInfoToken.getUserPersonCode());
        List<CoreDptInfo> dptlist = dptInfoDao.queryByDptCode(personInfoDO.getPersonOrgCode());
        if(CommonSysConstant.PERSON_CLASS_THREE.equals(personInfoDO.getPersonClass())){
            dptlist = dptInfoDao.queryAllRecordByLevel();
        }

        if( this.checkListEmpty(dptlist)){
            return resultList;
        }
        for (CoreDptInfo coreDptInfo : dptlist) {
            String orgCode = coreDptInfo.getDptOrgCode();
            DptInfoLevelVO dptInfoLevelVO = this.covertDOToVO(coreDptInfo);
            resultList.add(dptInfoLevelVO);
            if(CommonSysConstant.ORG_CODE_TYPE_5.equals(orgCode)){
                //企业特殊处理
                this.getSubDptComList(dptInfoLevelVO);

            }else{
                this.getSubDptList(dptInfoLevelVO);
            }
        }
        return resultList;
    }

    private void getSubDptComList(DptInfoLevelVO dptInfoLevelVO) {
        if(dptInfoLevelVO == null){
            return;
        }
        String dptCode = dptInfoLevelVO.getDptCode();
        List<String>  dptCodeList = dptSubInfoDao.queryCodebyParentCode(dptCode);
        if(dptCodeList == null || dptCodeList.isEmpty()){
            return;
        }
        List<CoreDptInfo>  dptDOList = dptInfoDao.queryByCodeList(dptCodeList);
        if(dptDOList == null || dptDOList.isEmpty()){
            return;
        }
        List<DptInfoLevelVO> voList = new ArrayList<DptInfoLevelVO>();
        for (CoreDptInfo dptDO : dptDOList) {
            DptInfoLevelVO vo = this.covertDOToVO(dptDO);
            voList.add(vo);
            this.getSubDptComList(vo);
        }
        dptInfoLevelVO.setSubDptList(voList);
    }

    private void getSubDptComCodeList(String dptCode, List<String> allDptCodeList) {
        if(StrUtil.isBlank(dptCode)){
            return;
        }
        allDptCodeList.add(dptCode);
        List<String>  dptCodeList = dptSubInfoDao.queryCodebyParentCode(dptCode);
        if(dptCodeList == null || dptCodeList.isEmpty()){
            return;
        }
        for (String subDptCode : dptCodeList) {
            this.getSubDptComCodeList(subDptCode, allDptCodeList);
        }
    }

    @Override
    public List<DptUserVo> getDptListWithUser(String orgCode,CoreUser token){
        //获取当前用户所属机构信息
        List<DptInfoLevelVO> dptTreeList = getOwerDptList(orgCode,token);
        List<DptUserVo> resultList = new ArrayList<DptUserVo>();
        this.getOwerDptListWithUser(dptTreeList, resultList);
        //回调查询部门下所属用户
//        return getUserByDpt(resultList);
        return resultList;
    }
    private List<UserMgInfoVO> getDptUserInfoWithUser(String dptCode) {
        List<UserMgInfoVO> resultList = new ArrayList<UserMgInfoVO>();
        List<CorePersonInfo> userDOList = personDao.getRecordByDptCode(dptCode,null);
        if(userDOList == null || userDOList.isEmpty()){
            return resultList;
        }
        for (CorePersonInfo personInfoDO : userDOList) {
            if(CommonSysConstant.CODE_NINE.equals(personInfoDO.getPersonClass())){
                continue;
            }
            CoreUser userDO = userDao.getRecordByPersonCode(personInfoDO.getPersonCode());
            if(userDO == null){
                logger.error("查询用户信息失败！PersonCode:"+personInfoDO.getPersonCode());
                continue;
            }
            String userCode = userDO.getUserCode();
            UserSubInfo userSubInfoDO = userSubInfoDao.selectByPrimaryKey(userCode);
            List<CoreRole> roleList = roleDao.queryRoleInfosByUserCode(userCode);
            UserMgInfoVO vo = this.genUserMgInfoVO(personInfoDO, userDO, userSubInfoDO,  roleList);
            resultList.add(vo);
        }
        return resultList;
    }
    //添加机构
    private void getOwerDptListWithUser(List<DptInfoLevelVO> dptTreeList,  List<DptUserVo> resultList) {
        if(dptTreeList == null || dptTreeList.isEmpty()){
            return;
        }
        for (DptInfoLevelVO dptInfoLevelVO : dptTreeList) {
            DptUserVo dptUserVo = new DptUserVo();
            String dptCode = dptInfoLevelVO.getDptCode();
            dptUserVo.setDptCode(dptCode);
            dptUserVo.setDptName(dptInfoLevelVO.getDptName());
            dptUserVo.setDptParentCode(dptInfoLevelVO.getDptParentCode());
            dptUserVo.setUserList(this.getDptUserInfoWithUser(dptCode));
            List<DptUserVo> resultSubList = new ArrayList<DptUserVo>();
            dptUserVo.setDptUserVos(resultSubList);
            resultList.add(dptUserVo);
            //处理人员位置和在线状态
            this.dealUserLineAncLocation(dptUserVo.getUserList());
            //添加子机构
            this.getOwerDptListWithUser(dptInfoLevelVO.getSubDptList(), resultSubList);
        }


    }

    //处理人员位置和在线状态
    private void dealUserLineAncLocation(List<UserMgInfoVO> userList) {
        if(userList == null || userList.isEmpty()){
            return;
        }
        for (UserMgInfoVO userMgInfoVO : userList) {
            if(userMgInfoVO == null){
                continue;
            }
            if( CommonSysConstant.PERSON_CLASS_ZERO.equals(userMgInfoVO.getPersonClass())
                    || CommonSysConstant.PERSON_CLASS_ONE.equals(userMgInfoVO.getPersonClass())
                    || CommonSysConstant.PERSON_CLASS_TWO.equals(userMgInfoVO.getPersonClass())){
                //用户
                String location = queryNewestLocation(userMgInfoVO.getUserCode(),userMgInfoVO.getPersonOrgCode());
                if(StrUtil.isNotEmpty(location)){
                    //如果有位置信息，重新判断在线状态
                    LocationVo locationVo = JSONObject.parseObject(String.valueOf(location),LocationVo.class);
                    long restTime = System.currentTimeMillis() - locationVo.getTimestamp();
                    if(restTime <= 60000){
                        userMgInfoVO.setIsOnline("1");
                    }else{
                        userMgInfoVO.setIsOnline("0");
                    }
                    userMgInfoVO.setLocation(locationVo);
                }
            }else{
                String tokenKey = CommonSysConstant.PERSON_TOKEN+":"+userMgInfoVO.getPersonOrgCode()+":"
                        +CommonSysConstant.getTokenUserTypeByPersonClass(userMgInfoVO.getPersonClass())+":"+userMgInfoVO.getUserCode();
                logger.info("当前用户token为：{}",tokenKey);
                if(redisUtils.hasKey(tokenKey)){
                    userMgInfoVO.setIsOnline("1");
                }else{
                    userMgInfoVO.setIsOnline("0");
                }
                userMgInfoVO.setUserRealName("（管理员）".concat(userMgInfoVO.getUserRealName()));
            }
        }

    }

    /**
     * 查询最新的位置信息
     * @param userCode
     * @return
     */
    private String queryNewestLocation(String userCode,String dptCode){
        Set<String> keySet = redisUtils.keys("location:"+dptCode+":"+userCode+":*");
        if(ObjectUtil.isNotEmpty(keySet)){
            Long timestamp = keySet.stream().mapToLong(x -> Long.parseLong(x.split(":")[3])).max().getAsLong();
            String key = "location:"+dptCode+":"+userCode+":"+timestamp;
            if(redisUtils.hasKey(key)){
                return String.valueOf(redisUtils.get(key));
            }
        }
        return null;
    }


//    private List<DptUserVo> getUserByDpt(List<DptInfoLevelVO> list){
//        List<DptUserVo> result = new ArrayList<>();
//        for (DptInfoLevelVO vo : list){
//            String dptCode = vo.getDptCode();
//            List<UserMgInfoVO> userTotalList = new ArrayList<>();
//            //查询用户
//            List<UserMgInfoVO> userList = getDptUserInfo(dptCode);
//            //查询管理员
//            List<UserMgInfoVO> userMgList = queryMgListByDptCode(dptCode);
//            for(UserMgInfoVO userMgInfoVO : userList){
//                String key = "location:"+vo.getDptCode()+":"+userMgInfoVO.getUserCode();
//                if(redisUtils.hasKey(key)){
//                    userMgInfoVO.setIsOnline("1");
//                    userMgInfoVO.setLocation(String.valueOf(redisUtils.get(key)));
//                }else{
//                    userMgInfoVO.setIsOnline("0");
//                }
//                userTotalList.add(userMgInfoVO);
//            }
//            for(UserMgInfoVO userMgVO : userMgList){
//                String key = CommonSysConstant.PERSON_TOKEN+":"+userMgVO.getPersonOrgCode()+":"+CommonSysConstant.PERSON_GLY12_FLAG+":"+userMgVO.getUserCode()+"*";
//                if(redisUtils.hasKey(key)){
//                    userMgVO.setIsOnline("1");
//                }else{
//                    userMgVO.setIsOnline("0");
//                }
//                userTotalList.add(userMgVO);
//            }
//            List<DptUserVo> dptUserVos = null;
//            if(ObjectUtil.isNotEmpty(vo.getSubDptList())){
//                dptUserVos = getUserByDpt(vo.getSubDptList());
//            }
//            result.add(DptUserVo.builder().dptCode(dptCode).dptName(vo.getDptName())
//                    .dptParentCode(vo.getDptParentCode()).userList(userTotalList).dptUserVos(dptUserVos).build());
//        }
//        return result;
//    }



    @Override
    public void changePasswordByUserCode(MgPasswordQUERY requestInfo, CoreUser userInfoToken) {
        if (StrUtil.hasBlank(requestInfo.getUserCode(), requestInfo.getUserPassword(),
                requestInfo.getOldPassword())) {
            throw new ValidateException("必传参数校验不通过！");
        }
        String userCode = requestInfo.getUserCode();
        String oldPassword = requestInfo.getOldPassword();
        List<CoreUser> userInfoList = userDao.getCheckUserInfo(userCode, oldPassword);
        if (ObjectUtil.isNull(userInfoList) || userInfoList.isEmpty()) {
            throw new ValidateException("用户原始密码错误！");
        }
        if (userInfoList.size() > 1) {
            throw new ValidateException("获取到多个用户信息！");
        }
        CoreUser userInfo = userInfoList.get(0);
        userInfo.setUserPassword(requestInfo.getUserPassword());
        TableCommonDataUtil.dealCrtUpdTableField(userInfoToken.getUserCode(), userInfo);
        userDao.updatePassword(userInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addUserOprInfo(UserMgAddQUERY requestInfo, CoreUser userInfoToken) {
        String currentUserCode = userInfoToken.getUserCode();
        if (StrUtil.hasBlank( requestInfo.getUserPassword(),
                requestInfo.getUserRealName(), requestInfo.getUserMobile(), requestInfo.getRoleCode())) {
            throw new ValidateException("必传参数校验不通过！");
        }
        if(CommonSysConstant.CODE_ZERO.equals(requestInfo.getAddFlag())){
            //编辑
            String  userCode = requestInfo.getUserCode();
            String userMobile = requestInfo.getUserMobile();
            if(StrUtil.isBlank(userCode)){
                throw new ValidateException("编辑用户信息，用户账号不能为空！");
            }
            CoreUser userDO = userDao.selectByUserCode(userCode);
            if(null == userDO){
                throw new ValidateException("查询人员信息失败！");
            }
            CorePersonInfo personInfoDO = personDao.getRecordByPersonCode(userDO.getUserPersonCode());
            if(personInfoDO == null ){
                throw new ValidateException("查询人员详情信息失败！");
            }

            userDO.setUserCode(userCode);
            userDO.setUserPassword(requestInfo.getUserPassword());
            personInfoDO.setPersonCode(userCode);
            userDO.setUserPersonCode(userCode);
            userDO.setUserMobile(userMobile);
            personInfoDO.setPersonMobile(userMobile);
            userDO.setUserRealName(requestInfo.getUserRealName());
            userDO.setUserDisplayName(requestInfo.getUserRealName());
            personInfoDO.setPersonRealName(requestInfo.getUserRealName());
            UserSubInfo subInfoDO = userSubInfoDao.selectByPrimaryKey(userCode);
            if(subInfoDO!=null){
                subInfoDO.setUserEmail(requestInfo.getUserEmail());
                userSubInfoDao.updateByPrimaryKey(subInfoDO);
            }else{
                subInfoDO.setUserCode(userCode);
                subInfoDO.setUserEmail(requestInfo.getUserEmail());
                userSubInfoDao.insert(subInfoDO);
            }
            middleUserRoleDao.deleteByUserCode(userCode);
            CoreMiddleUserRole record = new CoreMiddleUserRole();
            record.setMiddleUserCode(userCode);
            record.setMiddleRoleCode(requestInfo.getRoleCode());
            TableCommonDataUtil.dealCrtUpdTableField(currentUserCode, userDO, personInfoDO, record);
            middleUserRoleDao.insert(record);
            userDao.updateByPrimaryKeySelective(userDO);
            personDao.updateByPrimaryKeySelective(personInfoDO);

        }else{
            //新增
            String userCode = requestInfo.getUserCode();
            String userMobile = requestInfo.getUserMobile();
            if(StrUtil.isBlank(userCode)){
                userCode = userMobile;
            }
            CoreUser result = userDao.selectByUserCode(userCode);
            if(result != null){
                throw new ValidateException("账号已存在，请重新输入！");
            }
            CoreUser userDO = new CoreUser();
            userDO.setUserCode(userCode);
            userDO.setUserPassword(requestInfo.getUserPassword());
            CorePersonInfo personInfoDO = new CorePersonInfo();
            personInfoDO.setPersonCode(userCode);
            userDO.setUserPersonCode(userCode);
            userDO.setUserMobile(userMobile);
            personInfoDO.setPersonMobile(userMobile);
            userDO.setUserRealName(requestInfo.getUserRealName());
            userDO.setUserDisplayName(requestInfo.getUserRealName());
            personInfoDO.setPersonRealName(requestInfo.getUserRealName());
            CorePersonInfo currentPersonInfo = personDao.getRecordByPersonCode(userInfoToken.getUserPersonCode());
            //新增机构 或修改
            List<CoreDptInfo> dptInfoDOList = dptInfoDao.queryByDptCode(currentPersonInfo.getPersonOrgCode());
            if( !this.checkListEmpty(dptInfoDOList)){
                CoreDptInfo dptInfoDO = dptInfoDOList.get(0);
                personInfoDO.setPersonOrgCode(dptInfoDO.getDptCode());
                personInfoDO.setPersonOrgName(dptInfoDO.getDptName());
            }
            personInfoDO.setPersonOldName(personInfoDO.getPersonRealName());
            userDO.setUserDelFlag(CommonSysConstant.CODE_ZERO);
            userDO.setUserStatus(CommonSysConstant.CODE_ONE);
            userDO.setUserJobFlag(CommonSysConstant.CODE_ZERO);
            personInfoDO.setPersonDelFlag(CommonSysConstant.CODE_ZERO);
            personInfoDO.setPersonJobFlag(CommonSysConstant.CODE_ZERO);
            personInfoDO.setPersonStatus(CommonSysConstant.CODE_ONE);
            UserSubInfo subInfo = userSubInfoDao.selectByPrimaryKey(userCode);
            if(null == subInfo){
                UserSubInfo subInfoDO = new UserSubInfo();
                subInfoDO.setUserCode(userCode);
                subInfoDO.setUserEmail(requestInfo.getUserEmail());
                userSubInfoDao.insert(subInfoDO);
            }
            CoreMiddleUserRole record = new CoreMiddleUserRole();
            record.setMiddleUserCode(userCode);
            String roleCode = requestInfo.getRoleCode();
            record.setMiddleRoleCode(roleCode);
            personInfoDO.setPersonClass(CommonSysConstant.PERSON_CLASS_FIVE);
//            List<CoreOperate> operateList = operatorDao.queryRecorRoleCode(requestInfo.getRoleCode());
            if(CommonSysConstant.ROLE_CODE_YYS.equals(roleCode)){
                personInfoDO.setPersonClass(CommonSysConstant.PERSON_CLASS_NINE);
                CorePersonInfo tokenPerson = personDao.getRecordByPersonCode(userInfoToken.getUserPersonCode());
                if(tokenPerson != null){
                    personInfoDO.setPersonOrgCode(tokenPerson.getPersonOrgCode());
                    personInfoDO.setPersonOrgName(tokenPerson.getPersonOrgName());
                }else{
                    personInfoDO.setPersonOrgCode(CommonSysConstant.UNKNOW_DPT_CODE);
                    personInfoDO.setPersonOrgName(CommonSysConstant.UNKNOW_DPT_NAME);
                }
            }
//            if(operateList.size()>0){
//                for (CoreOperate operate : operateList) {
//                    if(CommonSysConstant.OPR_CODE_YYS.equals(operate.getOperateCode())){
//                        personInfoDO.setPersonClass(CommonSysConstant.PERSON_CLASS_NINE);
//                        personInfoDO.setPersonOrgCode(CommonSysConstant.UNKNOW_DPT_CODE);
//                        personInfoDO.setPersonOrgName(CommonSysConstant.UNKNOW_DPT_NAME);
//                        break;
//                    }
//                }
//            }
            TableCommonDataUtil.dealCrtUpdTableField(currentUserCode, userDO, personInfoDO, record);
            middleUserRoleDao.insert(record);
            userDao.insertSelective(userDO);
            personDao.insertSelective(personInfoDO);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delOperatorGrop(List<String> roleCodeList, CoreUser userInfoToken) {
        if(this.checkListEmpty(roleCodeList)){
            throw new ValidateException("必传参数校验不通过！");
        }
        int recordsNum = middleUserRoleDao.queryNumByRoleCodes(roleCodeList);
        if(recordsNum > 0 ){
            throw new ValidateException("该权限分组已被相关管理员占用，请先删除相关管理员信息！");
        }
        middleOperateRoleDao.deleteByRoleCodes(roleCodeList);
        String currentUserCode = userInfoToken.getUserCode();
        Map<String, Object> roleMap = new HashMap<String, Object>();
        roleMap.put("userCode", currentUserCode);
        roleMap.put("roleCodeList", roleCodeList);
        roleDao.deleteByRoleCodeList(roleMap);

    }

    @Override
    public MgInfoVO catOperatorGrop(String roleCode) {
        if(StrUtil.isBlank(roleCode)){
            throw new ValidateException("权限分组编码不能为空！");
        }
        CoreRole roleInfo = roleDao.getByRoleCode(roleCode);
        if(roleInfo == null){
            throw new ValidateException("查询不到权限分组数据！");
        }
        MgInfoVO vo = new MgInfoVO();
        vo.setRoleCode(roleInfo.getRoleCode());
        vo.setRoleName(roleInfo.getRoleName());
        List<Map<String,String>> operCodeList = middleOperateRoleDao.queryOperCodeListByRoleCode(roleCode);
        vo.setOperCodeList(operCodeList);
        return vo;
    }

    @Override
    public List<UserMgInfoVO> queryMgListByDptCode(String dptCode){
        if(StrUtil.isEmpty(dptCode)){
            throw new ValidateException(500,"部门Code为空");
        }
        CorePersonInfo personInfo = new CorePersonInfo();
        personInfo.setPersonOrgCode(dptCode);
        personInfo.setPersonClass("4");
        //查询一级管理员
        List<CorePersonInfo> personList1 = personDao.getRecordByDptAndClass(personInfo);
        personInfo.setPersonClass("5");
        logger.info("查询条件为："+personInfo.toString());
        List<CorePersonInfo> personList2 = personDao.getRecordByDptAndClass(personInfo);
        List<UserMgInfoVO> resultList = new ArrayList<>();
        for (CorePersonInfo corePersonInfo : personList1) {
            resultList.add(UserMgInfoVO.builder().userCode(corePersonInfo.getPersonCode()).userMobile(corePersonInfo.getPersonMobile()).personClass(corePersonInfo.getPersonClass())
                    .userRealName("（管理员）"+corePersonInfo.getPersonRealName()).personOrgCode(corePersonInfo.getPersonOrgCode()).build());
        }
        for (CorePersonInfo corePersonInfo : personList2) {
            resultList.add(UserMgInfoVO.builder().userCode(corePersonInfo.getPersonCode()).userMobile(corePersonInfo.getPersonMobile()).personClass(corePersonInfo.getPersonClass())
                    .userRealName("（管理员）"+corePersonInfo.getPersonRealName()).personOrgCode(corePersonInfo.getPersonOrgCode()).build());
        }
        return resultList;
    }

    @Override
    public List<UserMgInfoVO> getLocationUsers(CoreUser token) {
        List<UserMgInfoVO> resultList = new ArrayList<UserMgInfoVO>();
        // 查询登录用户所属保安和警察信息
        List<String> allDptCodeList = new ArrayList<String>();
        List<CorePersonInfo> userDOList = new ArrayList<>();
        CorePersonInfo personInfo = personDao.getRecordByUserCode(token.getUserCode());
        if(personInfo != null
                && CommonSysConstant.PERSON_CLASS_THREE.equals(personInfo.getPersonClass())){
            //超级管理员
            List<CoreDptInfo> dptInfoList = dptInfoDao.queryAllRecord();
            for(CoreDptInfo dptInfo : dptInfoList){
                userDOList.addAll(personDao.getRecordByDptCode(dptInfo.getDptCode(),token.getUserRealName()));
            }
        }else{
            String dptCode = dptInfoDao.getDptCodeByUserCode(token.getUserCode());
            if(StrUtil.isBlank(dptCode)){
                throw new ServiceException(500,"查询机构为空");
            }
            CoreDptInfo dptInfoDO = dptInfoDao.queryByDptCode(dptCode).isEmpty()
                    ?  null :  dptInfoDao.queryByDptCode(dptCode).get(0);
            if(ObjectUtil.isNull(dptInfoDO) ){
                throw new ServiceException(500,"查询机构为空");
            }
            //添加子机构代码
            this.getSubDptDOCodeList(allDptCodeList, dptInfoDO);
            for(String dpt : allDptCodeList){
                userDOList.addAll(personDao.getRecordByDptCodeAndUser(dpt,token.getUserRealName()));
            }
        }
        if (userDOList == null || userDOList.isEmpty()) {
            return resultList;
        }
        for (CorePersonInfo personInfoDO : userDOList) {
            //只需要保安和警察信息
            CoreUser userDO = userDao.getRecordByPersonCode(personInfoDO.getPersonCode());
            if (userDO == null) {
                logger.error("查询用户信息失败！PersonCode:" + personInfoDO.getPersonCode());
                continue;
            }
            if (CommonSysConstant.PERSON_CLASS_TWO.equals(personInfoDO.getPersonClass())
                    && CommonSysConstant.CODE_ZERO.equals(userDO.getUserStatus())) {
                //警察 已删除用户不查询
                logger.info("该警察用户状态无效!" + userDO.getUserCode());
                continue;
            }
            String userCode = userDO.getUserCode();
            UserSubInfo userSubInfoDO = userSubInfoDao.selectByPrimaryKey(userCode);
//            List<CoreRole> roleList = roleDao.queryRoleInfosByUserCode(userCode);
//            UserMgInfoVO vo = this.genUserMgInfoVO(personInfoDO, userDO, userSubInfoDO,  roleList);
            UserMgInfoVO vo = this.genUserMgInfoVO(personInfoDO, userDO, userSubInfoDO, null);
            if (vo == null) {
                continue;
            }
            String tokenKey = CommonSysConstant.PERSON_TOKEN + ":" + vo.getPersonOrgCode() + ":"
                    + CommonSysConstant.getTokenUserTypeByPersonClass(vo.getPersonClass()) + ":" + vo.getUserCode();
            if (redisUtils.hasKey(tokenKey)) {
                vo.setIsOnline("1");
            } else {
                vo.setIsOnline("0");
            }
            String location = queryNewestLocation(vo.getUserCode(),vo.getPersonOrgCode());
            if(StrUtil.isNotEmpty(location)){
                //如果有位置信息，重新判断在线状态
                LocationVo locationVo = JSONObject.parseObject(String.valueOf(location),LocationVo.class);
                long restTime = System.currentTimeMillis() - locationVo.getTimestamp();
                if(restTime <= 60000){
                    vo.setIsOnline("1");
                }else{
                    vo.setIsOnline("0");
                }
                vo.setLocation(locationVo);
            }
//            String key = "location:" + vo.getPersonOrgCode() + ":" + vo.getUserCode();
//            if (redisUtils.hasKey(key)) {
//                vo.setLocation(JSONObject.parseObject(String.valueOf(redisUtils.get(key)),LocationVo.class));
//            }
            resultList.add(vo);
        }
        return resultList;
    }


    // empty true
    private boolean checkListEmpty(List list){
        if(list == null || list.isEmpty()){
            return true;
        }
        return false;
    }

    @Override
    public List<MgRoleVO> getRoleOperateInfo(String roleType) {
        List<MgRoleVO>  resultList = new ArrayList<MgRoleVO>();
        List<CoreRole> roleDOList = null;
        switch (roleType) {
            case "0":
                roleDOList = roleDao.queryRoleInfosByRoleStaus(roleType);
                break;
            case "1":
                roleDOList = roleDao.queryRoleInfosByRoleStaus(roleType);
                break;
            case "9":
                roleDOList = roleDao.queryALLRoleInfos();
                break;
            default:
                throw new ValidateException("无相应类型的权限分组信息！");
        }
        if(roleDOList!=null && roleDOList.size()>0){
            for (CoreRole roleDO : roleDOList) {
                MgRoleVO roleVO = new MgRoleVO();
                roleVO.setRoleCode(roleDO.getRoleCode());
                roleVO.setRoleName(roleDO.getRoleName());
                resultList.add(roleVO);
            }
        }
        return resultList;
    }

    //部门管理 新增或修改人员和部门信息
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changeUserROInfo(UserMgInfoQUERY requestInfo, CoreUser userInfoToken) {
        CoreUser userDO = null;
        CorePersonInfo personInfoDO = null;
        String userCode = requestInfo.getUserCode();
        String userMobile = requestInfo.getUserMobile();

        if (StrUtil.isBlank(requestInfo.getPersonOrgCode()) || StrUtil.isBlank(userMobile)) {
            throw new ValidateException("部门信息和手机号码不能缺失！");
        }
        if(!Validator.isMobile(userMobile)){
            throw new ValidateException("手机号格式不正确！");
        }

        if (StrUtil.isBlank(requestInfo.getUserMobile())) {
            throw new ValidateException("电话不能缺失！");
        }
        if(CommonSysConstant.CODE_ONE.equals(requestInfo.getAddFlag())){
            //新增人员
            int recordNum = userDao.getRecordNumByMobile(userMobile);
            if(recordNum > 0){
                throw new ValidateException("该手机号也被注册！");
            }
            if(StrUtil.isBlank(userCode)){
                userCode = userMobile;
            }
            userDO = new CoreUser();
            userDO.setUserCode(userCode);
            personInfoDO = new CorePersonInfo();
            personInfoDO.setPersonCode(userCode);
            userDO.setUserPersonCode(userCode);
            userDO.setUserPassword(CommonSysConstant.DEFAULT_PASSWORD);
            userDO.setUserMobile(requestInfo.getUserMobile());
            personInfoDO.setPersonMobile(requestInfo.getUserMobile());
            userDO.setUserRealName(requestInfo.getUserRealName());
            userDO.setUserDisplayName(requestInfo.getUserRealName());
            personInfoDO.setPersonRealName(requestInfo.getUserRealName());
            //新增机构 或修改
            List<CoreDptInfo> dptInfoDOList = dptInfoDao.queryByDptCode(requestInfo.getPersonOrgCode());
            if( !this.checkListEmpty(dptInfoDOList)){
                CoreDptInfo dptInfoDO = dptInfoDOList.get(0);
                if(!CommonSysConstant.ORG_CODE_POLICE.equals(dptInfoDO.getDptOrgCode())){
                    throw new ValidateException("新增人员只能新增警务人员，请检查归属部门代码！");
                }
                personInfoDO.setPersonOrgCode(dptInfoDO.getDptCode());
                personInfoDO.setPersonOrgName(dptInfoDO.getDptName());
            }else{
                throw new ValidateException("该部门编码不存在，请检查！");
            }
            //修改人员职务信息
            requestInfo.setPersonPostCode(requestInfo.getPersonPostCode());
            requestInfo.setPersonPostName(requestInfo.getPersonPostName());
            UserSubInfo subInfoDO = new UserSubInfo();
            subInfoDO.setUserCode(userCode);
            subInfoDO.setUserPhotoUrl(requestInfo.getUserPhotoUrl());
            userSubInfoDao.insert(subInfoDO);
            personInfoDO.setPersonClass(CommonSysConstant.PERSON_CLASS_TWO);
        }else {
            //修改人员信息
            if (StrUtil.isBlank(userCode)) {
                throw new ValidateException("修改人员信息，用户编码不能缺失！");
            }
            if( StrUtil.isBlank(requestInfo.getPersonOrgCode())){
                throw new ValidateException("入参校验失败，部门代码不能为空！");
            }
            userDO = userDao.getRecordByUserCode(userCode, null);
            if(ObjectUtil.isNull(userDO)){
                throw new ValidateException("查询人员信息失败！");
            }
            personInfoDO = personDao.getRecordByPersonCode(userDO.getUserPersonCode());
            if(personInfoDO == null ){
                throw new ValidateException("查询人员详情信息失败！");
            }

            //修改手机号
            if( !StrUtil.equals(userMobile, userDO.getUserMobile())){
                int recordNum = userDao.getRecordNumByMobile(userMobile);
                if(recordNum > 0){
                    throw new ValidateException("该手机号也被注册！");
                }
                String uerMobileStr = requestInfo.getUserMobile();
                userDO.setUserMobile(requestInfo.getUserMobile());
                personInfoDO.setPersonMobile(requestInfo.getUserMobile());
            }
            //修改姓名
            if(StrUtil.isNotBlank(requestInfo.getUserRealName())
                    && !StrUtil.equals(requestInfo.getUserRealName(), userDO.getUserRealName())){
                userDO.setUserRealName(requestInfo.getUserRealName());
                userDO.setUserDisplayName(requestInfo.getUserRealName());
                personInfoDO.setPersonRealName(requestInfo.getUserRealName());
            }

            //修改部门信息
            if( !StrUtil.equals(requestInfo.getPersonOrgCode(), personInfoDO.getPersonOrgCode())){
                //新增机构 或修改
                List<CoreDptInfo> dptInfoDOList = dptInfoDao.queryByDptCode(requestInfo.getPersonOrgCode());
                if(dptInfoDOList != null && dptInfoDOList.size()> 0 ){
                    CoreDptInfo dptInfoDO = dptInfoDOList.get(0);
                    personInfoDO.setPersonOrgCode(dptInfoDO.getDptCode());
                    personInfoDO.setPersonOrgName(dptInfoDO.getDptName());
                    personDao.updateByPrimaryKey(personInfoDO);
                }else{
                    throw new ValidateException("该部门编码不存在，请检查！");
                }
            }

            //修改头像或邮箱信息
            if(StrUtil.isNotBlank(requestInfo.getUserPhotoUrl())){
                UserSubInfo subInfoDO = userSubInfoDao.selectByPrimaryKey(userCode);

                if(subInfoDO == null ){
                    subInfoDO = new UserSubInfo();
                    subInfoDO.setUserCode(userCode);
                    if(StrUtil.isNotBlank(requestInfo.getUserPhotoUrl())){
                        subInfoDO.setUserPhotoUrl(requestInfo.getUserPhotoUrl());
                    }
                    userSubInfoDao.insert(subInfoDO);
                }else {
                    if( !StrUtil.equals(requestInfo.getUserPhotoUrl(), subInfoDO.getUserPhotoUrl()) ){
                        if(StrUtil.isNotBlank(requestInfo.getUserPhotoUrl())){
                            subInfoDO.setUserPhotoUrl(requestInfo.getUserPhotoUrl());
                        }
                        userSubInfoDao.updateByPrimaryKey(subInfoDO);
                    }

                }
            }
            //修改人员职务信息
            if(StrUtil.isNotBlank(requestInfo.getPersonPostCode())
                    && !StrUtil.equals(requestInfo.getPersonPostCode(), personInfoDO.getPersonPostCode())){
                requestInfo.setPersonPostCode(requestInfo.getPersonPostCode());
            }
            if(StrUtil.isNotBlank(requestInfo.getPersonPostName())
                    && !StrUtil.equals(requestInfo.getPersonPostName(), personInfoDO.getPersonPostName())){
                requestInfo.setPersonPostName(requestInfo.getPersonPostName());
            }
//            //修改权限分组信息
//            if(( requestInfo.getDelRoleCodeList() != null &&  requestInfo.getDelRoleCodeList().size()>0) ){
//                List<String> roleCodeDelList = requestInfo.getDelRoleCodeList();
//                if(roleCodeDelList!= null &&  roleCodeDelList.size() >0 ){
//                    Map<String, Object> map = new HashMap<String, Object>();
//                    map.put("userCode", userCode);
//                    map.put("roleCodeList", roleCodeDelList);
//                    middleUserRoleDao.deleteByRoleCodeList(map);
//                }
//
//            }
        }
//        //新增权限分组信息
//        List<String> roleCodeAddList = requestInfo.getAddRoleCodeList();
//        if(roleCodeAddList!= null &&  roleCodeAddList.size() >0 ){
//            for (String roleCodeAdd : roleCodeAddList) {
//                CoreMiddleUserRole record = new CoreMiddleUserRole();
//                record.setMiddleUserCode(userCode);
//                record.setMiddleRoleCode(roleCodeAdd);
//                TableCommonDataUtil.dealCrtUpdTableField(userInfoToken.getUserCode(), record);
//                middleUserRoleDao.insert(record);
//            }
//        }
        personInfoDO.setPersonOldName(personInfoDO.getPersonRealName());
        userDO.setUserDelFlag(CommonSysConstant.CODE_ZERO);
        userDO.setUserStatus(CommonSysConstant.CODE_ONE);
        userDO.setUserJobFlag(CommonSysConstant.CODE_ZERO);
        personInfoDO.setPersonDelFlag(CommonSysConstant.CODE_ZERO);
        personInfoDO.setPersonJobFlag(CommonSysConstant.CODE_ZERO);
        personInfoDO.setPersonStatus(CommonSysConstant.CODE_ONE);
        TableCommonDataUtil.dealCrtUpdTableField(userInfoToken.getUserCode(), userDO, personInfoDO);
        if(CommonSysConstant.CODE_ONE.equals(requestInfo.getAddFlag())){
            userDao.insert(userDO);
            personDao.insert(personInfoDO);
        }else{
            userDao.updateByPrimaryKey(userDO);
            personDao.updateByPrimaryKey(personInfoDO);
        }

    }

    private UserMgInfoVO genUserMgInfoVO(CorePersonInfo personInfoDO, CoreUser userDO, UserSubInfo userSubInfoDO, List<CoreRole> roleList) {
        UserMgInfoVO mgUserVO = new UserMgInfoVO();
        mgUserVO.setPersonOrgCode(personInfoDO.getPersonOrgCode());
        mgUserVO.setPersonOrgName(personInfoDO.getPersonOrgName());
        mgUserVO.setPersonPostCode(personInfoDO.getPersonPostCode());
        mgUserVO.setPersonPostName(personInfoDO.getPersonPostName());
        mgUserVO.setPersonCardType(personInfoDO.getPersonCardType());
        mgUserVO.setPersonCardNumber(personInfoDO.getPersonCardNumber());
        mgUserVO.setPersonSex(personInfoDO.getPersonSex());
        mgUserVO.setPersonBirthDate(personInfoDO.getPersonBirthDate());
        mgUserVO.setPersonBirthAddress(personInfoDO.getPersonBirthAddress());
        mgUserVO.setPersonClass(personInfoDO.getPersonClass());
        mgUserVO.setAuditStatus(personInfoDO.getPersonJobFlag());
        mgUserVO.setUserCode(userDO.getUserCode());
        mgUserVO.setUserPassword(userDO.getUserPassword());
        mgUserVO.setUserRealName(userDO.getUserRealName());
        mgUserVO.setUserMobile(userDO.getUserMobile());
        if(userSubInfoDO != null){
            mgUserVO.setUserEmail(userSubInfoDO.getUserEmail());
            mgUserVO.setUserPhotoUrl(userSubInfoDO.getUserPhotoUrl());
            mgUserVO.setUserExpireTime(DateUtil.format(userSubInfoDO.getUserExpireTime(),
                    "yyyy-MM-dd HH:mm:ss"));
        }
        List<MgRoleVO> roleVOList = new ArrayList<MgRoleVO>();
        mgUserVO.setRoleVOList(roleVOList);
       if(roleList == null || roleList.isEmpty()){
           return mgUserVO;
       }
        for (CoreRole roleDO : roleList) {
            MgRoleVO roleVO = new MgRoleVO();
            roleVO.setRoleCode(roleDO.getRoleCode());
            roleVO.setRoleName(roleDO.getRoleName());
            roleVOList.add(roleVO);
        }
        return mgUserVO;
    }
}
